package com.amon.amonplayer.crash;

import android.app.Application;
import android.os.Looper;

public class CrashMonitor {
    private static final CrashMonitor instance = new CrashMonitor();
    private Application mApplication;

    private CrashMonitor() {

    }

    public void init(Application application) {
        this.mApplication = application;
        Looper.myQueue().addIdleHandler(() -> {
            mApplication.registerActivityLifecycleCallbacks(LifecycleCallback.getInstance());
            ActivityManager activityManager = new ActivityManager();
            final ProcessFinisher processFinisher = new ProcessFinisher(mApplication, true, activityManager);
            final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
            Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
                e.printStackTrace();
                processFinisher.finishLastActivity(t);
                processFinisher.endApplication();
//                if (defaultHandler != null) {
//                    defaultHandler.uncaughtException(t, e);
//                }
            });
            return false;
        });
    }

    public static CrashMonitor getInstance() {
        return instance;
    }
}
